package com.token.iot.bratterycharging.boss.web;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.outstanding.framework.base.TransactionLogger;
import com.outstanding.framework.container.springmvc.WebContext;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.core.ReturnCode;
import com.token.base.order.api.OrderVO;
import com.token.base.order.api.PayInfoDTO;
import com.token.base.order.api.PayItemDTO;
import com.token.iot.bratterycharging.boss.service.OrderServcice;

@Controller
@RequestMapping("/pay")
public class PayController {

	@Autowired
	private OrderServcice orderService;
	
	
	@ResponseBody
	@RequestMapping(value = "/show.do")
	public PayInfoDTO show() throws PendingException {
		String agentId = (String) WebContext.getSession().getAttribute("_agentid");
		if (agentId == null) {
			String mid = (String) WebContext.getSession().getAttribute("_merchantid");
			if (mid == null) {
				throw new PendingException(ResCode.OperNotLogin);
			}else {
				return orderService.queryPay(null,mid);
			}
		}else {
			return orderService.queryPay(agentId,null);
		}
		
	}
	
	
	/**
	 * 代理商设置支付产品
	 * 
	 * @param dto
	 * @return
	 * @throws PendingException
	 */
	@ResponseBody
	@RequestMapping(value = "/set.do")
	public ReturnCode setPayItem(@RequestBody PayItemStrDTO str) throws PendingException {
		TransactionLogger.debug("staring setPayItem " + String.valueOf(str == null) + " ");
		String agentId = (String) WebContext.getSession().getAttribute("_agentid");
		if (agentId == null) {
				String mid = (String) WebContext.getSession().getAttribute("_merchantid");
				if (mid == null) {
					throw new PendingException(ResCode.OperNotLogin);
				}
		}
		if(StringUtils.isBlank(str.getId())) {
			List<PayItemDTO> dto = str.toPayItem();
			if (dto.get(0) != null) {
				dto.get(0).setAgentId(agentId);
			} else {
				throw new PendingException(ResCode.PayItemParamError);
			}
			return orderService.addPayItem(dto);
		}else {
			List<PayItemDTO> dto = str.toPayItem();
			if (dto.get(0) != null) {
				dto.get(0).setAgentId(agentId);
			} else {
				throw new PendingException(ResCode.PayItemParamError);
			}
			return orderService.updatePayItem(str.getId(),dto);
		}
	}
}
